<template>
  <div class="payment-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="开单支付"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 支付内容 -->
    <div class="payment-content">
      <!-- 费用明细 -->
      <div class="cost-section">
        <h3>费用明细</h3>
        <div class="cost-list">
          <div 
            v-for="item in orderItems" 
            :key="item.id"
            class="cost-item"
          >
            <div class="item-info">
              <div class="item-name">{{ item.name }}</div>
              <div class="item-desc">{{ item.description }}</div>
            </div>
            <div class="item-price">¥{{ item.price }}</div>
          </div>
        </div>
        
        <!-- 总费用 -->
        <div class="total-section">
          <div class="total-row">
            <span class="total-label">合计：</span>
            <span class="total-amount">¥{{ totalAmount }}</span>
          </div>
        </div>
      </div>

      <!-- 支付方式选择 -->
      <div class="payment-method-section">
        <h3>支付方式</h3>
        <div class="payment-methods">
          <div 
            v-for="method in paymentMethods" 
            :key="method.id"
            class="payment-method"
            :class="{ active: selectedMethod === method.id }"
            @click="selectPaymentMethod(method.id)"
          >
            <div class="method-info">
              <van-icon :name="method.icon" size="24" :color="method.color" />
              <span class="method-name">{{ method.name }}</span>
            </div>
            <van-radio 
              v-model="selectedMethod"
              :name="method.id"
              :checked-value="method.id"
              @click.stop="selectPaymentMethod(method.id)"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 底部支付按钮 -->
    <div class="payment-footer">
      <div class="footer-info">
        <div class="payment-amount">
          <div class="amount-text">
            <span class="amount-label">支付金额</span>
            <span class="amount-value">¥{{ totalAmount }}</span>
          </div>
        </div>
      </div>
      <van-button 
        type="primary" 
        size="large" 
        :disabled="!selectedMethod"
        @click="confirmPayment"
        class="pay-btn"
      >
        确认支付
      </van-button>
    </div>


  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Toast, Dialog } from 'vant'
import apiService, { type PayOrderApplicationRequest, type PaymentResultDto } from '@/api'
import { useUserStore } from '@/stores/user'

/**
 * 开单支付页面组件
 * 提供多种支付方式，完成开单支付流程
 */

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const selectedMethod = ref('')

/**
 * 订单项目接口
 */
interface OrderItem {
  id: number
  name: string
  description: string
  price: number
}

/**
 * 支付方式接口
 */
interface PaymentMethod {
  id: string
  name: string
  icon: string
  color: string
}

/**
 * 订单项目数据
 * 从路由参数获取或使用默认数据
 */
const orderItems = ref<OrderItem[]>([])

/**
 * 支付方式列表
 */
const paymentMethods = ref<PaymentMethod[]>([
  {
    id: 'wechat',
    name: '微信支付',
    icon: 'wechat',
    color: '#07c160'
  },
  {
    id: 'alipay',
    name: '支付宝支付',
    icon: 'alipay',
    color: '#1677ff'
  },
  {
    id: 'bankcard',
    name: '银行卡支付',
    icon: 'credit-pay',
    color: '#ff6b35'
  }
])

/**
 * 计算总金额
 */
const totalAmount = computed(() => {
  const total = orderItems.value.reduce((sum, item) => sum + item.price, 0)
  return total.toFixed(2)
})

/**
 * 点击返回按钮
 */
const onClickLeft = () => {
  router.back()
}

/**
 * 选择支付方式
 * @param methodId 支付方式ID
 */
const selectPaymentMethod = (methodId: string) => {
  selectedMethod.value = methodId
}

/**
 * 确认支付
 */
const confirmPayment = () => {
  if (!selectedMethod.value) {
    Toast('请选择支付方式')
    return
  }

  const selectedMethodName = paymentMethods.value.find(
    method => method.id === selectedMethod.value
  )?.name

  Dialog.confirm({
    title: '确认支付',
    message: `确认使用${selectedMethodName}支付 ¥${totalAmount.value} 吗？`,
    confirmButtonText: '确认支付',
    cancelButtonText: '取消'
  }).then(() => {
    processPayment()
  }).catch(() => {
    // 用户取消支付
  })
}

/**
 * 处理支付流程
 */
const processPayment = async () => {
  Toast.loading({
        message: '正在支付...',
        forbidClick: true,
        duration: 0
      })

  try {
    // 获取订单数据
    const orderDataStr = route.query.orderData as string
    if (!orderDataStr) {
      Toast.clear()
      Toast.fail('订单数据不存在')
      return
    }

    const orderData = JSON.parse(orderDataStr)
    if (!orderData.orderId) {
      Toast.clear()
      Toast.fail('订单ID不存在')
      return
    }

    // 获取选中的支付方式名称
    const selectedMethodName = paymentMethods.value.find(
      method => method.id === selectedMethod.value
    )?.name || '未知支付方式'

    // 检查用户是否已登录
    if (!userStore.isLoggedIn) {
      Toast('请先登录后再进行支付')
      router.push('/login')
      return
    }

    // 构造支付请求数据
    const paymentRequest: PayOrderApplicationRequest = {
      orderApplicationId: parseInt(orderData.orderId),
      userId: userStore.userId,
      paymentMethod: selectedMethodName,
      paymentAmount: parseFloat(totalAmount.value),
      paymentTransactionId: generateTransactionId()
    }

    // 调用后端支付API
    const result = await apiService.payOrderApplication(paymentRequest)
    Toast.clear()

    if (result.code === 200 && result.data) {

      
      // 显示支付成功提示
      Toast.success({
        message: '支付成功！',
        duration: 1500
      })
      
      // 1.5秒后跳转到支付成功页面
      setTimeout(() => {
        goToOrderDetail()
      }, 1500)
    } else {
      // 支付失败
      Toast.fail(result.message || '支付失败，请重试')
      console.error('支付失败:', result.message)
    }
  } catch (error) {
    Toast.clear()
    Toast.fail('支付处理异常，请重试')
    console.error('支付处理异常:', error)
  }
}

/**
 * 生成交易号
 */
const generateTransactionId = (): string => {
  const timestamp = Date.now()
  const random = Math.floor(Math.random() * 10000)
  return `PAY${timestamp}${random}`
}

/**
 * 跳转到开单记录页面（支付成功页面）
 */
const goToOrderDetail = () => {
  // 构造订单详情数据
  const orderDetailData = {
    orderId: Date.now().toString(), // 生成订单ID
    status: 'paid', // 已支付状态
    createTime: new Date().toISOString(),
    hospitalName: '智慧医疗中心',
    applicant: '王小明',
    totalAmount: totalAmount.value,
    projects: orderItems.value.map(item => ({
      id: item.id,
      name: item.name,
      description: item.description,
      price: item.price
    }))
  }
  
  // 跳转到开单记录页面（支付成功页面）
  router.push({
    path: '/order-history',
    query: {
      showDetail: 'true',
      orderDetail: JSON.stringify(orderDetailData)
    }
  })
}

/**
 * 从路由参数加载订单数据
 */
const loadOrderData = () => {
  try {
    const orderDataStr = route.query.orderData as string
    if (orderDataStr) {
      const orderData = JSON.parse(orderDataStr)
      orderItems.value = orderData.items || []
      
      // 验证订单数据完整性
      if (!orderData.orderId) {
        Toast('订单信息不完整')
        router.back()
        return
      }
      
      // 检查是否有项目
      if (orderItems.value.length === 0) {
        Toast('订单中没有检查项目')
        router.back()
        return
      }
      
      // 检查总金额是否为0
      if (orderData.totalAmount === 0) {
        Toast('订单金额为0，无法支付')
        router.back()
        return
      }
      

    } else {
      Toast('未找到订单数据')
      router.back()
    }
  } catch (error) {
    console.error('解析订单数据失败:', error)
    Toast('订单数据加载失败')
    router.back()
  }
}

/**
 * 页面挂载时初始化数据
 */
onMounted(() => {
  userStore.initUserInfo()
  loadOrderData()
})
</script>

<style scoped>
.payment-container {
  height: 100%;
  max-height: 100vh;
  background-color: #f7f8fa;
  display: flex;
  flex-direction: column;
  max-width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

.payment-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  padding-bottom: 80px; /* 为底部按钮留出空间 */
}

/* 费用明细样式 */
.cost-section {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.cost-section h3 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0 0 16px 0;
}

.cost-list {
  margin-bottom: 16px;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.cost-item:last-child {
  border-bottom: none;
}

.item-info {
  flex: 1;
  margin-right: 12px;
}

.item-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.item-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.item-price {
  font-size: 14px;
  font-weight: bold;
  color: #ff6b35;
}

.total-section {
  border-top: 1px solid #eee;
  padding-top: 12px;
}

.total-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-label {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.total-amount {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b35;
}

/* 支付方式样式 */
.payment-method-section {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.payment-method-section h3 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0 0 16px 0;
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.payment-method {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #eee;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.payment-method:hover {
  border-color: #1989fa;
  background-color: #f8f9ff;
}

.payment-method.active {
  border-color: #1989fa;
  background-color: #f8f9ff;
}

.method-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.method-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

/* 底部支付按钮样式 */
.payment-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 12px 16px;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  gap: 12px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
  /* 确保在手机屏幕内 */
  max-width: 100%;
  box-sizing: border-box;
}

.footer-info {
  flex: 1;
}

.payment-amount {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.amount-text {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 2px;
}

.amount-label {
  font-size: 12px;
  color: #999;
  font-weight: 400;
  line-height: 1;
}

.amount-value {
  font-size: 20px;
  font-weight: bold;
  color: #ff6b35;
  line-height: 1.2;
}

.pay-btn {
  min-width: 120px;
  height: 44px;
  border-radius: 22px;
  font-weight: bold;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .payment-content {
    padding: 12px;
  }
  
  .cost-section,
  .payment-method-section {
    padding: 12px;
  }
  
  .payment-footer {
    padding: 8px 12px;
  }
  
  .success-content {
    padding: 24px 16px 16px;
    max-width: 280px;
  }
}
</style>